﻿using System;
using System.Web;
using System.Web.UI;
using System.Web.Security;

namespace Billing2
{
    public partial class Default : Page
    {
        protected override void OnPreRender(EventArgs e)
        {
            //this.Page.ViewStateEncryptionMode = ViewStateEncryptionMode.Always;
            this.Page.RegisterRequiresViewStateEncryption();
            base.OnPreRender(e);
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            //EPPLog.Logger.Debug(ClsPasswordHelper.Encrypt("admin"));
            //EPPLog.Logger.Debug(ClsPasswordHelper.Encrypt("mike"));
            //EPPLog.Logger.Debug(ClsPasswordHelper.Encrypt("tom"));
            //EPPLog.Logger.Debug(ClsPasswordHelper.Encrypt("kit"));
            //EPPLog.Logger.Debug(ClsPasswordHelper.Encrypt("test"));

            string username = txtUserName.Text.Trim();
            string password = txtPassword.Text.Trim();
            string errormsg = "";
            if (!ClsUserProfile.ValidUser(username, password, ref errormsg))
            {
                password = "";
                ucHighlight1.ErrorMessage = errormsg;
                return;
            }
            //change seesion ID after login
            EPPLog.Logger.Info("SessionID (before login): " + Session.SessionID);
            Session.Abandon();
            HttpCookie cookie = new HttpCookie("ASP.NET_SessionId", "");
            cookie.Secure = true;
            cookie.HttpOnly = true;
            this.Response.Cookies.Add(cookie);
            AddRedirCookie(username, password);
            this.Response.Redirect("login.aspx");
            password = "";
        }

        private void AddRedirCookie(string username, string password)
        {
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, "LoginId", DateTime.Now, DateTime.Now.AddSeconds(60), false,
                MyLib.HexUtility.BytesToHex(System.Text.Encoding.ASCII.GetBytes(username + "|" + password)));
            string encryptedText = FormsAuthentication.Encrypt(ticket);
            HttpCookie cookie = new HttpCookie("__LOGINCOOKIE__", encryptedText);
#if !DEV
            cookie.Secure = true;
#endif
            cookie.HttpOnly = true;
            this.Response.Cookies.Add(cookie);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            this.Response.AppendHeader("Cache-Control", "no-store");
            this.Response.AppendHeader("Cache-Control", "no-cache");
            this.Response.AppendHeader("X-Content-Type-Options", "nosniff");
            this.Response.AppendHeader("Strict-Transport-Security", "max-age=31536000; includeSubDomains; preload");
#if !DEV
            this.Response.AppendHeader("Content-Security-policy", "default-src https: data: 'unsafe-inline' 'unsafe-eval'");
#endif

            //anti CSRF
            if (!this.Page.IsPostBack)
            {
                string anti_csrf = ClsPasswordHelper.Encrypt("anti_csrf" + MyLib.Rand.RandomInt(0, int.MaxValue - 1).ToString()).Replace("=", "").Replace("/", "").Replace("+", "");
                this.request_id.Value = anti_csrf;
                this.Session["request_id"] = anti_csrf;
            }
            else
            {
                if (this.Session["request_id"] == null || this.request_id.Value != this.Session["request_id"].ToString())
                {
                    EPPLog.Logger.Error(Common.EscapeLog(String.Format("Detecterd CSRF1. RawUrl={0} request_id={1} inSession={2}", this.Request.RawUrl, this.request_id.Value, this.Session["request_id"])));
                    base.Response.Redirect("logout.aspx", true);
                    return;
                }
            }

            ucHighlight1.CloseAll();

            string referrer = this.Request.UrlReferrer == null ? "" : this.Request.UrlReferrer.ToString();
            if (referrer != "" && !Global.IsAllowDomain(referrer))
            {
                EPPLog.Logger.Error(String.Format("Detecterd CSRF at Deault.aspx. referrer={0}", referrer));
                //base.Response.Redirect("default.aspx", true);
                return;
            }

            if (!this.Page.IsPostBack)
            {
                //lblHeader.Text = Microsoft.Security.Application.Encoder.HtmlEncode(ClsApplicationConfiguration.Header);
                //lblFooter.Text = Microsoft.Security.Application.Encoder.HtmlEncode(ClsApplicationConfiguration.Footer);
            }

        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            ViewStateUserKey = Session.SessionID;
        }

    }
}